// pages/cart/cart.js
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ShoppingCart:[    
      {
        "id": 3,
        "uid": 1,
        "servicename": "做饭服务",
        "serviceprice": 199,
        "serviceid": 17,
        "picurl": "http://192.168.101.65:9000/photos/1/servicepic/10a80123538ed681d323cc26494060ad.png",
        "createat": "2024-12-08T10:23:58.000+00:00",
        "specification": "餐点份量/单餐（1-2人）/99.0"
      }
    ],
    cartPrice:'',

    
  },
  
  
  /**
   * 生命周期函数--监听页面加载
   */
  comSpecs2() {
    this.data.ShoppingCart.forEach(shopping => {
      try {
        // 确保 specificationContent 字符串是有效的 JSON
        shopping.specification = shopping.specification.split("/"); // 解析并重新赋值
        console.log("22223222");
        console.log(shopping.specification[2]);
        
      } catch (error) {
        console.error(`Error parsing specificationContent for service ${service.productname}:`, error);
      }
    });
    
    // 更新整个 Services 数据
    this.setData({
      ShoppingCart: this.data.ShoppingCart
    });
    console.log(33333);
    console.log(this.data.ShoppingCart);
    console.log(111);
    console.log(111);
  },

  getBuy1(){
    wx.request({
      url: 'http://localhost:9001/wx/getShoppingCart',
      method:'GET',
      withCredentials: true, 
      success:(res)=>{
        this.setData({
          ShoppingCart:res.data.data
        })
        this.comSpecs2();
        const totalPirce2 =this.data.ShoppingCart.reduce((sum, item) => {
          const price = parseFloat(item.specification[2]); // 转换为数字
          return sum + price;
        },0)
        this.setData({
          cartPrice:totalPirce2
        }),
        console.log(totalPirce2);
      }
    })
    this.setData({
      show:true
    })
},
  deleteCart(event) {
    const { position, instance } = event.detail;
  
    // 手动获取 item 数据
    const item = event.currentTarget.dataset.item || this.cachedItem;
  
    if (!item) {
      console.error('item 未定义，请检查数据绑定');
      return;
    }
    this.cachedItem = item; // 缓存 item，防止数据丢失
    const serviceid = item.serviceid;
  
    switch (position) {
      case 'left':
      case 'cell':
        instance && instance.close();
        break;
      case 'right':
        Dialog.confirm({
          message: '确定删除吗？',
        }).then(() => {
          wx.request({
            url: `http://localhost:9001/wx/deleteShoppingCart/${serviceid}`,
            method: 'GET',
            withCredentials: true, 
            success: (res) => {
              console.log('删除成功:', res);
              instance && instance.close();
              this.getBuy1();
              
            },
            fail: (err) => {
              console.error('删除失败:', err);
            },
          });
        });
        break;
    }
  },
  
  cleanCart(){
    Dialog.confirm({
      message: '确定清空清单？',
    }).then(() => {
      console.log(33333);
      wx.request({
        url: 'http://localhost:9001/wx/clearShoppingCart',
        withCredentials: true, 
        success:(res)=>{
          console.log(res);
          this.getBuy1();
          this.backBut();
          wx.showToast({
           title: res.data.data,
           icon: 'none',
           duration: 1500
         });
        }
      })
    });

  },

  subAll(){
    wx.setStorage({
      key:'allCart',
        data:{
         orderdetailList:this.data.ShoppingCart,
         totalPrice:this.data.cartPrice,
         paymentMethod: "支付宝",
        } ,
        success:(res)=>{
          wx.navigateTo({
            url: '/pages/older/older',
            success:(res3)=>{
              console.log(res3);
            }
          }) 
        }
    })

   if(this.data.ShoppingCart==null){
    wx.showToast({
      title: '清单为空',
      icon: 'none',
      duration: 1500
    });
   }
   else{
  console.log(this.data.ShoppingCart);
    this.data.ShoppingCart.forEach(ShoppingCart=>{
      //  console.log(ShoppingCart.specification);
         const specification=`${ShoppingCart.specification[0]}/${ShoppingCart.specification[1]}/${ShoppingCart.specification[2]}`;
         console.log(specification);
         ShoppingCart.specification = specification;
    })
    console.log(this.data.ShoppingCart);
    wx.request({
      url: 'http://localhost:9001/wx/submitShoppingCart',
      withCredentials: true, 
      method:'POST',
      data:{
        totalPrice:this.data.cartPrice,
        paymentMethod: "支付宝",
        orderdetailList:this.data.ShoppingCart,
      },
      success:(res2)=>{
         wx.setStorage({
           key:'oriderid',
           data: res2.data.data.orderid
           
         })
              wx.navigateTo({
                url: '/pages/older/older',
                success:(res3)=>{
                  console.log(res3);
                }
              })
      }
    })
   }
  
  },
  onLoad(options) {
     this.getBuy1();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})